﻿using System;
using System.Web;
using FranceTriple.Dal;
using TeamFranceTriple.Config;

namespace TeamFranceTriple
{
    public partial class ShoutBox : BaseUserControl
    {
        private Int32 MaxMessage = TeamFranceTripleConfig.WebConfig.shoutbox.MaxNumberOfMessage;
        private Int32 AutoRefreshFrequency = TeamFranceTripleConfig.WebConfig.shoutbox.AutoRefresh;

        protected void Page_Load(object sender, EventArgs e)
        {
            ShoutboxMessageObjectDataSource.SelectParameters["MaxNumberOfMessage"].DefaultValue = MaxMessage.ToString();
            ShoutboxMessageObjectDataSource.SelectParameters["requesterTimeZone"].DefaultValue = UserProfile.GetUserProfile().TimeZone;

            //if (AutoRefreshFrequency == 0)
            //    ShoutboxTimer1.Enabled = false;
            //else if (!Request.Browser.IsMobileDevice && ThisMaster.Requester.IsAuthenticated)
            //    ShoutboxTimer1.Interval = AutoRefreshFrequency * 1000;

            if (Session["AnonymousID"] == null)
            {
                ShoutTextBox1.Visible = true;
                SendButton.Visible = true;
                SmiliesButton.Visible = true;
            }
            else
            {
                ShoutTextBox1.Visible = false;
                SendButton.Visible = false;
                SmiliesButton.Visible = false;
            }

            if (ShoutBoxListLink != null)
                ShoutBoxListLink.NavigateUrl = String.Format("/{0}/shoutboxlist/?shoutboxpagenumber=1", ThisMaster.Requester.Culture);
            if (ShoutBoxListLink2 != null)
                ShoutBoxListLink2.NavigateUrl = String.Format("/{0}/shoutboxlist/?shoutboxpagenumber=1", ThisMaster.Requester.Culture);
        }

        protected void Page_PreRender(object sender, EventArgs e)
        {
            ShowSmiliesLiteral.Text = ShoutboxDal.GetSmilies("DoSmilie");
        }

        protected void SendButton_Click(object sender, EventArgs e)
        {
            if (!this.Page.IsValid) return;

            if (ThisMaster.Requester.IsAuthenticated)
            {
                if (ShoutTextBox1.Text != String.Empty)
                {
                    ShoutboxDal.CreateEntity(new FranceTriple.Dal.ShoutBox() { MessageShoutBox = ShoutTextBox1.TextToHtml(), UserNameAuthorShoutBox = ThisMaster.Requester.Profile.UserName });

                    Cache.Remove(ShoutboxMessageObjectDataSource.CacheKeyDependency);
                    ShoutboxMessageListView.DataBind();

                    ShoutTextBox1.Text = String.Empty;
                }
            }
            else // tentative de hacking de la shoutbox : les utilisateurs anonymes n'ont pas le droit d'écrire
            {
                throw new HttpException(403, "Hacking try: Anonymous users are not allowed to write inside the shoutbox.");
            }
        }
    }
}
